import { Button, Checkbox, Form, Input } from 'antd';
import { FC } from "react"
// import "./index.css"
import { useNavigate } from "react-router-dom"
import * as api from "@/api"
import useStorage from "@/hooks/useStorage"
type Irule = {
  require?: boolean,
  message?: string,
  remember?: boolean,
  username?: string,
  password?:string,
  
  // vaildator:()=>void
}
// 校验用户名是否为空
let validatUsename = (rule:any,value:string) => {
  if (value !== "") {
    return Promise.resolve()
  } else {
    return Promise.reject(rule.message)
  }
}
// 校验密码是否符合基本规范
let vaildatPassword = (rule:any, value:string) => {
  // console.log(rule,value)
  let regExp = /[\-_\w\d]{3,10}/
  if (regExp.test(value)) {
    return Promise.resolve()
  } else {
    return Promise.reject(rule.message)
  }
}
let Login: FC = () => {
  let [, tokenMethod] = useStorage('tq-token')
  let [, userMethod] = useStorage('user--info')
  let [,permissionMethod]=useStorage('btn-permission')
  // 注意这里的声明,声明在函数内会报错,hook的错误,移到外面就好了
  let navigate = useNavigate()
  // 成功
  let onFinish = (values: Irule) => {
    // console.log("success", values)
    let {username,password}=values
    api.getLogin(username, password).then((res:any) => {
      console.log(res)
      if (res.data.state) {
        // localStorage.setItem('tq-token', res.data.token)
        //1.存token
        tokenMethod.set(res.data.token)
        //2.存用户信息
        userMethod.set(res.data.userInfo)
        //3.存按钮权限
        permissionMethod.set(res.data.permission)
      }
      navigate("/")
    })
  }
  // 失败
  let onFinishFailed = (errorInfo: any) => {
    // console.log("Failed",errorInfo)
  }

  return (
    <Form
      name="basic"
      labelCol={{ span: 2 }}
      wrapperCol={{ span: 5 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: 'Please输入用户名', validator:validatUsename}]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[
          {
            required: true,
            message: 'Please输入密码',
            validator: vaildatPassword
          }
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 2, span: 5 }}>
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 2, span: 5 }}>
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}

export default Login